<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧会话列表 -->
      <el-col :span="6">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>会话列表</span>
              <el-button type="primary" @click="createNewSession" plain>新建会话</el-button>
            </div>
          </template>
          <div class="session-list">
            <div
              v-for="session in sessionList"
              :key="session.sessionId"
              class="session-item"
              :class="{ active: currentSessionId === session.sessionId }"
              @click="switchSession(session.sessionId)"
            >
              <div class="session-title">{{ session.title || '新会话' }}</div>
              <div class="session-time">{{ formatTime(session.time) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧聊天区域 -->
      <el-col :span="18">
        <el-card class="chat-card">
          <template #header>
            <div class="card-header">
              <span>AI聊天助手</span>
              <el-button type="danger" @click="clearMessages" plain>清空对话</el-button>
            </div>
          </template>
          
          <!-- 聊天消息区域 -->
          <div class="chat-container" ref="chatContainer">
            <div v-if="messages.length === 0" class="empty-chat">
              <el-empty description="开始一个新的对话吧！" />
            </div>
            <div v-else class="message-list">
              <div v-for="(message, index) in messages" :key="index" class="message-item" :class="message.role">
                <div class="message-avatar">
                  <el-avatar :icon="message.role === 'user' ? UserFilled : Service" :size="40" />
                </div>
                <div class="message-content">
                  <div class="message-role">{{ message.role === 'user' ? '我' : 'AI助手' }}</div>
                  <div class="message-text" v-html="formatMessage(message.content)"></div>
                </div>
              </div>
              <div v-if="loading" class="message-item assistant">
                <div class="message-avatar">
                  <el-avatar :icon="Service" :size="40" />
                </div>
                <div class="message-content">
                  <div class="message-role">AI助手</div>
                  <div class="message-text">
                    <div class="typing-indicator">
                      <span></span>
                      <span></span>
                      <span></span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 输入区域 -->
          <div class="input-container">
            <el-input
              v-model="inputMessage"
              type="textarea"
              :rows="3"
              placeholder="输入您的问题..."
              :disabled="loading"
              @keyup.enter.ctrl="sendMessage"
            />
            <div class="button-container">
              <el-button type="primary" @click="sendMessage" :loading="loading" :disabled="!inputMessage.trim()">
                发送
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="AiChatInterface">
import { ref, onMounted, nextTick, computed } from 'vue';
import { UserFilled, Service } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { v4 as uuidv4 } from 'uuid';
import { marked } from 'marked';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';

// 配置marked和highlight.js
marked.setOptions({
  highlight: function(code, lang) {
    const language = hljs.getLanguage(lang) ? lang : 'plaintext';
    return hljs.highlight(code, { language }).value;
  },
  langPrefix: 'hljs language-',
  gfm: true,
  breaks: true
});

// 状态变量
const messages = ref([]);
const inputMessage = ref('');
const loading = ref(false);
const chatContainer = ref(null);
const sessionList = ref([]);
const currentSessionId = ref('');

// 创建新会话
const createNewSession = () => {
  const sessionId = uuidv4();
  sessionList.value.unshift({
    sessionId,
    title: '新会话',
    time: Date.now()
  });
  switchSession(sessionId);
};

// 切换会话
const switchSession = (sessionId) => {
  currentSessionId.value = sessionId;
  messages.value = []; // 清空当前消息
  // TODO: 加载历史消息
  loadSessionMessages(sessionId);
};

// 加载会话消息
const loadSessionMessages = async (sessionId) => {
  try {
    // TODO: 从后端加载会话消息
    // 这里是模拟加载
    messages.value = [];
  } catch (error) {
    ElMessage.error('加载会话消息失败');
    console.error(error);
  }
};

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || loading.value) return;
  
  if (!currentSessionId.value) {
    createNewSession();
  }
  
  const userMessage = inputMessage.value.trim();
  messages.value.push({
    role: 'user',
    content: userMessage
  });
  
  inputMessage.value = '';
  loading.value = true;
  
  // 滚动到底部
  await nextTick();
  scrollToBottom();
  
  try {
    // 创建EventSource连接
    const source = new EventSource(`/api/nursing/aiChat/chat?prompt=${encodeURIComponent(userMessage)}&sessionId=${currentSessionId.value}`);
    
    let aiResponse = '';
    
    source.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        if (data.choices && data.choices.length > 0) {
          const choice = data.choices[0];
          if (choice.delta && choice.delta.content) {
            aiResponse += choice.delta.content;
            
            // 如果这是第一次收到内容，添加一个新的消息
            if (messages.value.length === 0 || messages.value[messages.value.length - 1].role !== 'assistant') {
              messages.value.push({
                role: 'assistant',
                content: aiResponse
              });
            } else {
              // 更新现有消息
              messages.value[messages.value.length - 1].content = aiResponse;
            }
            
            // 滚动到底部
            scrollToBottom();
          }
        }
      } catch (error) {
        console.error('解析消息失败:', error);
      }
    };
    
    source.onerror = (error) => {
      console.error('EventSource错误:', error);
      source.close();
      loading.value = false;
      
      // 如果没有收到任何响应，添加错误消息
      if (!aiResponse) {
        messages.value.push({
          role: 'assistant',
          content: '抱歉，我遇到了一些问题，请稍后再试。'
        });
        scrollToBottom();
      }
    };
    
    source.addEventListener('end', () => {
      source.close();
      loading.value = false;
      
      // 更新会话标题（使用用户的第一条消息作为标题）
      if (sessionList.value.length > 0) {
        const session = sessionList.value.find(s => s.sessionId === currentSessionId.value);
        if (session && session.title === '新会话') {
          session.title = userMessage.length > 20 ? userMessage.substring(0, 20) + '...' : userMessage;
        }
      }
    });
  } catch (error) {
    console.error('发送消息失败:', error);
    loading.value = false;
    messages.value.push({
      role: 'assistant',
      content: '抱歉，发送消息时出现错误，请稍后再试。'
    });
    scrollToBottom();
  }
};

// 清空当前对话
const clearMessages = () => {
  messages.value = [];
};

// 格式化消息（将Markdown转换为HTML）
const formatMessage = (text) => {
  return marked(text);
};

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  return date.toLocaleString();
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
    }
  });
};

// 初始化
onMounted(() => {
  createNewSession();
});
</script>

<style scoped>
.app-container {
  height: calc(100vh - 120px);
  overflow: hidden;
}

.box-card, .chat-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.session-list {
  overflow-y: auto;
  flex: 1;
}

.session-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}

.session-item:hover {
  background-color: #f5f7fa;
}

.session-item.active {
  background-color: #ecf5ff;
}

.session-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.session-time {
  font-size: 12px;
  color: #999;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background-color: #f5f7fa;
}

.empty-chat {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.message-list {
  display: flex;
  flex-direction: column;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
}

.message-item.user {
  flex-direction: row-reverse;
}

.message-avatar {
  margin: 0 10px;
}

.message-content {
  max-width: 70%;
}

.message-role {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.message-text {
  padding: 10px;
  border-radius: 5px;
  word-break: break-word;
}

.message-item.user .message-text {
  background-color: #ecf5ff;
}

.message-item.assistant .message-text {
  background-color: #fff;
}

.input-container {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
}

.button-container {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

/* 打字指示器样式 */
.typing-indicator {
  display: flex;
  align-items: center;
}

.typing-indicator span {
  height: 8px;
  width: 8px;
  background-color: #3498db;
  border-radius: 50%;
  display: inline-block;
  margin: 0 2px;
  opacity: 0.4;
  animation: typing 1s infinite;
}

.typing-indicator span:nth-child(1) {
  animation-delay: 0s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0% {
    opacity: 0.4;
    transform: scale(1);
  }
  50% {
    opacity: 1;
    transform: scale(1.2);
  }
  100% {
    opacity: 0.4;
    transform: scale(1);
  }
}

/* 让代码块样式更好看 */
:deep(pre) {
  background-color: #f6f8fa;
  border-radius: 6px;
  padding: 16px;
  overflow: auto;
}

:deep(code) {
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 85%;
}

:deep(p) {
  margin: 0 0 10px 0;
}

:deep(ul), :deep(ol) {
  padding-left: 20px;
}

:deep(blockquote) {
  border-left: 4px solid #dfe2e5;
  padding-left: 16px;
  color: #6a737d;
  margin: 0 0 16px 0;
}

:deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 16px;
}

:deep(th), :deep(td) {
  border: 1px solid #dfe2e5;
  padding: 6px 13px;
}

:deep(th) {
  background-color: #f6f8fa;
}
</style>
